package com.service.impl;

import com.dto.CreatorStatDTO;
import com.dto.StatDTO;
import com.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.ClientMapper;
import com.mapper.GoodsEntityMapper;
import com.mapper.OrderMapper;
import com.mapper.RefundMapper;
import com.mysql.cj.exceptions.DataReadException;
import com.service.OrderService;
import com.vo.OrderClientVO;
import com.vo.OrderRefundVO;
import com.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private GoodsEntityMapper goodsEntityMapper;

    @Autowired
    private RefundMapper refundMapper;

    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public PageBean<Order> getAll(Integer pageIndex, Integer pageSize, OrderVO orderVO) {
        if (orderVO.getCname() != null && orderVO.getCname() != "") {
            orderVO.setCids(clientMapper.selectByCname(orderVO.getCname()));
        }

        if (orderVO.getGname() != null && orderVO.getGname() != "") {
            orderVO.setGids(goodsEntityMapper.selectByGname(orderVO.getGname()));
        }


        System.out.println(orderVO);

        PageHelper.startPage(pageIndex, pageSize);

        List<Order> list = orderMapper.selectAll(orderVO);

        PageInfo<Order> pageInfo = new PageInfo<>(list);

        PageBean<Order> pageBean = new PageBean<>(
                pageIndex,
                pageSize,
                pageInfo.getPages(),
                (int) pageInfo.getTotal(),
                pageInfo.getList()
        );

        return pageBean;
    }

    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void add(OrderClientVO orderClientVO) {
        Order order = new Order();
        Client newClient = new Client();

        Integer gid = goodsEntityMapper.selectGidByGname(orderClientVO.getGname());
        Integer cid = 0;
        //获取当前系统时间作为订单时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate = dateFormat.format(date);

        //判断客户是否已存在
        Client client = clientMapper.selectClientByCname(orderClientVO.getCname());
        if (client == null) {
            //添加客户信息
            newClient.setCname(orderClientVO.getCname());
            newClient.setPostal(orderClientVO.getPostal());
            newClient.setSite(orderClientVO.getSite());
            newClient.setContacts(orderClientVO.getContacts());
            newClient.setPhone(orderClientVO.getPhone());
            newClient.setEmail(orderClientVO.getEmail());
            newClient.setBank(orderClientVO.getBank());
            newClient.setBanknumber(orderClientVO.getBanknumber());
            newClient.setState("启用");
            newClient.setGrade(1);
            newClient.setScale(orderClientVO.getScale());
            newClient.setArea(orderClientVO.getArea());
            newClient.setLegal(orderClientVO.getLegal());
            newClient.setLegalphone(orderClientVO.getLegalphone());
            newClient.setFinancecontacts(orderClientVO.getFinancecontacts());
            newClient.setFinancephone(orderClientVO.getFinancephone());
            newClient.setCreation(orderClientVO.getCreation());
            newClient.setCreationtime(systemDate);
            newClient.setVersions(1);
            newClient.setAmendtime(systemDate);
            clientMapper.add(newClient);

            //获取新加客户的id值
            cid = newClient.getCid();

        } else {
            cid = client.getCid();
            clientMapper.delete(0, cid);
            clientMapper.updateState("启用", cid);
        }

        //添加订单信息
        order.setOrdernumber(orderClientVO.getOrdernumber());
        order.setCreator(orderClientVO.getCreation());
        order.setEarnest(orderClientVO.getEarnest());
        order.setUnpatdamount((orderClientVO.getGrossamount() - orderClientVO.getEarnest()));
        order.setGrossamount(orderClientVO.getGrossamount());
        order.setNumber(orderClientVO.getNumber());
        order.setOrdertime(systemDate);
        if (order.getUnpatdamount().equals(0)) {
            order.setState("已完成");
        } else {
            order.setState("待支付");
        }
        order.setGid(gid);
        order.setCid(cid);
        System.out.println("order=" + order);
        orderMapper.add(order);
    }

    @Override
    public void remove(int[] oids) {
        orderMapper.dalete(oids);
    }

    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void modify(Order order) {
        Integer cid = order.getCid();
        order.setUnpatdamount(order.getGrossamount() - order.getEarnest());
        if (order.getUnpatdamount().equals(0)) {
            order.setState("已完成");
            order.setRid(0);
        } else if (order.getEarnest().equals(0)) {
            order.setState("已退款");
            clientMapper.updateState("未启用", cid);
        } else {
            order.setState("待支付");
            order.setRid(0);
        }
        orderMapper.update(order);
    }

    @Override
    public String getOrderNumber() {
        int max = 0;
        List<String> orderNumber = orderMapper.selectOrderNumber();
        for (int i = 0; i < orderNumber.size(); i++) {
            String[] arrStr = orderNumber.get(i).split("-");
            if (max < Integer.parseInt(arrStr[1])) {
                max = Integer.parseInt(arrStr[1]);
            }
        }
        int newMax = max + 1;
        return "D-" + newMax;
    }

    @Override
    public void delivery(Order order) {
        orderMapper.updateState(order.getOid(), order.getGrossamount(), 0, "已完成");
    }

    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void refund(OrderRefundVO orderRefundVO) {
        orderMapper.updateState(orderRefundVO.getOid(), 0, orderRefundVO.getGrossamount(), "已退款");
        Refund refund = new Refund();
        refund.setGid(orderRefundVO.getGid());
        refund.setGname(orderRefundVO.getGoodsEntity().getGname());
        refund.setCause(orderRefundVO.getCause());
        //获取当前系统时间作为退款时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        refund.setRefundtime(dateFormat.format(date));
        refund.setBanknumber(orderRefundVO.getClient().getBanknumber());
        refundMapper.add(refund);
        orderMapper.addRid(refund.getRid(), orderRefundVO.getOid());
    }

    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public StatDTO stat(String month) {
        StatDTO statDTO = new StatDTO();
        statDTO.setCreatorStat(orderMapper.selectCreatorByOrderTime(month));
        statDTO.setStateStat(orderMapper.selectStateByOrderTime(month));
        return statDTO;
    }

    @Override
    public List<CreatorStatDTO> statYear(String year, String creator) {
        List<CreatorStatDTO> list = new ArrayList<>();

        for (int i = 1; i <= 12; i++) {
            CreatorStatDTO creatorStatDTO = new CreatorStatDTO();
            String time = "";
            if (i < 10) {
                time = year + "-0" + i;
            } else {
                time = year + "-" + i;
            }
            int sum = orderMapper.selectByCreatorAndOrdertime(time, creator);
            creatorStatDTO.setName(i + "");
            creatorStatDTO.setValue(sum + "");
            list.add(creatorStatDTO);
        }
        System.out.println("year=" + year);
        System.out.println("creator=" + creator);
        System.out.println("list=" + list);
        return list;
    }

    @Override
    public Employee getByCname(String ename) {
        return orderMapper.selectByEname(ename);
    }

    @Override
    public GoodsEntity getByGname(String gname) {
        return orderMapper.selectByGname(gname);
    }
}
